#!/usr/bin/env bash

# ===== 0) 可选：换源 =====
if [ -f "./cs.py" ]; then
  sudo python ./cs.py -r || true
fi

# ===== 1) 系统同步与基础组件 =====
sudo pacman -Syu --noconfirm
sudo pacman -S --needed --noconfirm paru unzip zip wget

# ===== 2) Docker =====
paru -S --needed --noconfirm docker docker-compose starship
user_to_add="${SUDO_USER:-$USER}"
sudo usermod -aG docker "$user_to_add" || true
sudo systemctl enable --now docker

# ===== 3) 图像格式支持 =====
sudo pacman -S --needed --noconfirm qt6-imageformats qt5-imageformats slirp4netns
paru -S --needed --noconfirm libdbusmenu-glib

# ===== 4) MariaDB =====
paru -S --needed --noconfirm mariadb
if [ ! -d /var/lib/mysql/mysql ]; then
  sudo mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
fi
sudo systemctl enable --now mariadb

# 安全初始化
# sudo mysql_secure_installation

# ===== 5) 输入法与字体 =====
paru -S --needed --noconfirm fcitx5-im fcitx5-chinese-addons fcitx5-pinyin-zhwiki
paru -S --needed --noconfirm \
  ttf-fira-code noto-fonts-emoji ttf-jetbrains-mono-nerd \
  wqy-microhei wqy-microhei-lite wqy-bitmapfont wqy-zenhei \
  ttf-arphic-ukai ttf-arphic-uming \
  adobe-source-han-sans-cn-fonts adobe-source-han-serif-cn-fonts \
  noto-fonts-cjk

# ===== 6) Python 配置脚本（用户态执行） =====
[ -f "./set_input.py" ] && python ./set_input.py || true
[ -f "./link.py" ] && [ -f "./user.json" ] && python ./link.py ./user.json || true

# 用户级服务：先重载，再启用（可选：立即启动）
systemctl --user daemon-reload || true
systemctl --user enable magic || true
# systemctl --user start magic || true

# ===== 7) Node.js 工具链 =====
paru -S --needed --noconfirm npm pnpm yarn

mkdir -p "$HOME/.npm" "$HOME/.npm/cache"
mkdir -p "$HOME/.pnpm/store" "$HOME/.pnpm/global/bin" "$HOME/.pnpm/cache" "$HOME/.pnpm/state" "$HOME/.pnpm/global"
mkdir -p "$HOME/.yarn/cache" "$HOME/.yarn/global" "$HOME/.yarn/link"

npm config set prefix "$HOME/.npm"
npm config set cache "$HOME/.npm/cache"
pnpm config set store-dir "$HOME/.pnpm/store"
pnpm config set global-bin-dir "$HOME/.pnpm/global/bin"
pnpm config set global-dir "$HOME/.pnpm/global"
pnpm config set cache-dir "$HOME/.pnpm/cache"
pnpm config set state-dir "$HOME/.pnpm/state"
yarn config set prefix "$HOME/.yarn"
yarn config set global-folder "$HOME/.yarn/global"
yarn config set cache-folder "$HOME/.yarn/cache"
yarn config set link-folder "$HOME/.yarn/link"

npm config set registry https://registry.npmmirror.com/
yarn config set registry https://registry.npmmirror.com/
pnpm config set registry https://registry.npmmirror.com/

echo
echo "✅ 初始化完成：Docker / MariaDB 已启动。"
echo "ℹ️ 第一次将当前用户加入 docker 组：重新登录，或在当前 shell 执行 'newgrp docker' 立即生效。"
